package main

import (
	"context"
	"fmt"
	pb2 "github.com/jonasngs/go_entry_task/protobuf3/pb"
	"log"
	"net"

	"github.com/jonasngs/go_entry_task/tcp_server/config"
	"github.com/jonasngs/go_entry_task/tcp_server/manager"
	"google.golang.org/grpc"
)

type tcpserver struct {
	pb2.UnimplementedUserManagerServer
}

var userManager *manager.Manager

func (s *tcpserver) LoadProfile(ctx context.Context, req *pb2.ProfileRequest) (*pb2.ProfileResponse, error) {
	sessionToken := req.GetSessionToken()
	user, err := userManager.Session.VerifySession(sessionToken)
	if err != nil {
		return nil, err
	}
	return &pb2.ProfileResponse{
		User: user,
	}, nil
}

func (s *tcpserver) Update(ctx context.Context, req *pb2.UpdateRequest) (*pb2.UpdateResponse, error) {
	nickname := req.GetNickname()
	profilePicture := req.GetProfilePicture() // Type image
	sessionToken := req.GetSessionToken()
	user, err := userManager.Session.VerifySession(sessionToken)
	if err != nil {
		return nil, err
	}

	err = userManager.User.UpdateProfilePicture(user.GetUsername(), sessionToken, profilePicture.GetData(), profilePicture.GetFileExtension())
	if err != nil {
		return &pb2.UpdateResponse{}, err
	}

	err = userManager.User.UpdateNickname(user.GetUsername(), sessionToken, nickname)
	if err != nil {
		return &pb2.UpdateResponse{}, err
	}
	return &pb2.UpdateResponse{}, nil
}

func (s *tcpserver) Login(ctx context.Context, req *pb2.LoginRequest) (*pb2.LoginResponse, error) {
	username := req.GetUsername()
	password := req.GetPassword()
	log.Printf("login user is : %v\n", username)
	err := userManager.Authentication.AuthenticateLogin(username, password)
	if err != nil {
		return &pb2.LoginResponse{
			SessionToken: "",
		}, err
	}
	newToken := userManager.Session.GenerateSessionToken()
	fmt.Println(newToken)
	userManager.Session.CreateSession(username, newToken)
	return &pb2.LoginResponse{
		SessionToken: newToken,
	}, nil
}

func main() {
	config.OpenConfigFile()
	log.Printf(config.GetTCPServer())
	lis, err := net.Listen("tcp", config.GetTCPServer())
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	userManager = manager.InitializeManager()

	var opts []grpc.ServerOption
	grpcServer := grpc.NewServer(opts...)
	pb2.RegisterUserManagerServer(grpcServer, &tcpserver{})
	grpcServer.Serve(lis)

}
